package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 *      使用注解@RestControllerAdvice，当控制层报异常时，会被捕获
 *
 *      使用@ExceptionHandler指定异常类型进行处理
 *          获取异常信息
 *          判断是否进行处理
 *          拆分异常信息，获得账号名，进行返回
 */

//@ControllerAdvice(annotations = {RestController.class, Controller.class})
//@ResponseBody
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> doSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException ex){

        //1.获取错误信息
        String message = ex.getMessage();
        log.info(message);
        //2.对错误信息进行判断，包含Duplicate entry则进行拆分
        //Duplicate entry '111' for key 'idx_username'
        if (message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            //3.将指定信息返回
            return R.error(split[2] + "已存在");
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> doCustomException(CustomException ex){

        //1.获取错误信息
        String message = ex.getMessage();
        log.info(message);
        //返回错误信息
        return R.error(message);
    }
}
